package kz.pvnhome.pimrestore.pim;

import java.util.List;

import android.content.ContentResolver;
import android.util.Log;
import android.widget.ProgressBar;

/**
 * Created: May 10, 2012 9:13:46 AM
 * @author victor
 */
public class PIMBackupUtils {
   private static final String TAG = "PIMBackupUtils";

   private ContactsLoadTask mTask;
   private ContactsInsertTask insertTask;

   public boolean loadContacts(String pimFileName, ProgressBar mProgress, ContactsLoadListener loadListener) {
      if (mTask == null && insertTask == null) {
         mTask = (ContactsLoadTask) new ContactsLoadTask(mProgress, loadListener).execute(pimFileName);
         return true;
      } else {
         return false;
      }
   }

   public void close() {
      cancelTasks();
   }

   private void cancelTasks() {
      if (mTask != null) {
         if (mTask.getStatus() != ContactsLoadTask.Status.FINISHED) {
            Log.d(TAG, "cancelLoadTask"); //$NON-NLS-1$
            mTask.cancel(true);
         }
         mTask = null;
      }
      if (insertTask != null) {
         if (insertTask.getStatus() != ContactsLoadTask.Status.FINISHED) {
            Log.d(TAG, "cancelInsertTask"); //$NON-NLS-1$
            insertTask.cancel(true);
         }
         insertTask = null;
      }
   }

   @SuppressWarnings("unchecked")
   public boolean insertContacts(List<ContactDTO> contactsList, ProgressBar mProgress, ContentResolver contentResolver, ContactsInsertListener contactsInsertListener) {
      if (mTask == null && insertTask == null) {
         insertTask = (ContactsInsertTask) new ContactsInsertTask(mProgress,  contentResolver, contactsInsertListener).execute(contactsList);
         return true;
      } else {
         return false;
      }
   }
}
